package com.example.shoppingdemo.Fragment;

import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.shoppingdemo.Adapter.HomeAdpter;

import com.example.shoppingdemo.R;
import com.example.shoppingdemo.Util.TextSwitchView;
import com.example.shoppingdemo.javaBean.Homebean;
import com.example.shoppingdemo.nslcommodity.CommodityModel;
import com.example.shoppingdemo.nslcommodity.IResult.CommodityRs;
import com.example.shoppingdemo.nslcommodity.IResult.ICommodityResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HomeFragment extends Fragment {
    private View view;
    private RecyclerView recyclerView;
    private HomeAdpter homeAdpter;
    private Context context;
    private Object MyDecoration;
    private List<CommodityModel> commodityModelList;
    //===============================
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private int currentItem;
    //记录上一次点的位置
    private int oldPosition = 0;
    //存放图片的id
    private int[] imageIds = new int[]{
            R.drawable.home_gg,
            R.drawable.home_gg2,
            R.drawable.home_gg3,
            R.drawable.home_gg4,
    };
    //存放图片的标题
    private String[] titles = new String[]{
            "广告1",
            "广告2",
            "广告3",
            "广告4",

    };
    private TextView title;
    private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home, container, false);
        //轮播广告方法
        setView();
        //文字轮播方法
        test1();


        return view;
    }

   //@RequiresApi(api = Build.VERSION_CODES.O)
    /*
    * 搜索框文字轮播方法
    * */
   public void test1() {
       TextSwitchView textSwitchView = (TextSwitchView) view.findViewById(R.id.switcher);
       //转速
       textSwitchView.setTextStillTime(4000);
   }

    @Override
    public void onViewCreated(@NonNull  View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //瀑布流方法
        initData();
    }
    private void initData() {
        commodityModelList=new ArrayList<>();
        ICommodityResult commodityResult=new CommodityRs(context);;
        commodityResult.onShopping(1,new CommodityRs.onShopResponse() {
            @Override
            public void onShopList(List<CommodityModel> commodityModels) {
                recyclerView = view.findViewById(R.id.recy_home_id);
                // 定义一个瀑布流的布局管理器
                StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
                // 设置布局管理器为瀑布流
                recyclerView.setLayoutManager(manager);
                homeAdpter= new HomeAdpter(requireContext());
                homeAdpter.setCommodityModels(commodityModelList);
                recyclerView.setAdapter(homeAdpter);
                //设置分隔线
                recyclerView.addItemDecoration((RecyclerView.ItemDecoration) MyDecoration);
                commodityModelList.clear();
                homeAdpter.setCommodityModels(commodityModels);
                homeAdpter.setXiangQ(new HomeAdpter.onXiangQ() {
                    @Override
                    public void onxiangqing(int position) {
                        //跳转商品详情
                    }
                });
                homeAdpter.notifyDataSetChanged();

            }
        });


    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyDecoration = new MyDecoration();


    }
    //轮播广告方法
    private void setView() {
        mViewPaper = (ViewPager) view.findViewById(R.id.vp);
        //显示的图片
        images = new ArrayList<ImageView>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        dots.add(view.findViewById(R.id.dot_3));
        dots.add(view.findViewById(R.id.dot_4));

        title = (TextView) view.findViewById(R.id.title);
        title.setText(titles[0]);
        //实例化适配器
        adapter = new ViewPagerAdapter();
        mViewPaper.setAdapter(adapter);
        mViewPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.drawable.ic_baidian);
                dots.get(oldPosition).setBackgroundResource(R.drawable.ic_huidian);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }


    /*定义的适配器*/
    public class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub

            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            return images.get(position);
        }

    }

    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }


    /**
     * 图片轮播任务
     * @author liuyazhuang
     *
     */
    private class ViewPageTask implements Runnable{
        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        };
    };
    private Handler handler=new Handler();

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if(scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }


}
    /*
* 分割线方法
* */
class MyDecoration extends RecyclerView.ItemDecoration {
    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(5, 5, 10, 10);
    }


    }